using System.Collections;
using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;

/// <summary>
/// 食物生成器
/// </summary>
public class FoodSpawner : MonoBehaviour
{
    /// <summary>
    /// 食物预制体
    /// </summary>
    [SerializeField]private GameObject foodPrefab;
    
    /// <summary>
    /// 创建食物定时器携程
    /// </summary>
    private Coroutine _spawnCoroutine;
    
    void Start()
    {
        // 当服务器启动后回调
        NetworkManager.Singleton.OnServerStarted += SpawnFoodStart;
    }

    /// <summary>
    /// 启动创建食物
    /// </summary>
    private void SpawnFoodStart()
    {
        // 移除回调
        NetworkManager.Singleton.OnServerStarted -= SpawnFoodStart;
        
        // 创建食物
        for (int i = 0; i < 30; i++)
            SpawnFood();
        // 启动创建食物定时器
        _spawnCoroutine = StartCoroutine(SpawnFoodTimer());
        
        // 当服务器断开停止创建食物
        NetworkManager.Singleton.OnServerStopped += b =>
        {
            StopCoroutine(_spawnCoroutine);
        };
    }

    /// <summary>
    /// 创建食物
    /// </summary>
    private void SpawnFood()
    {
        NetworkObject food = NetworkObjectPool.Singleton.GetNetworkObject(foodPrefab,GetRandomPos(),Quaternion.identity);
        // 设置源预制体
        food.GetComponent<Food>().foodPrefab = foodPrefab;
        food.Spawn();
    }

    /// <summary>
    /// 获得随机位置
    /// </summary>
    /// <returns></returns>
    private Vector3 GetRandomPos()
    {
        return new Vector3(Random.Range(-9, 9), Random.Range(-5, 5),0);
    }
    
    /// <summary>
    /// 生成食物定时器
    /// </summary>
    /// <returns></returns>
    private IEnumerator SpawnFoodTimer()
    {
        // 玩家大于零才产生食物
        while (true)
        {
            yield return new WaitForSeconds(2f);
            
            if(NetworkManager.Singleton.ConnectedClients.Count > 0)
                SpawnFood();
        }
    }
}
